<template>
  <div class="system-users">
    <div class="page-header">
      <h1 class="page-title">用户管理</h1>
      <el-button
        type="primary"
        @click="handleAddUser"
        v-permission="'system:user:add'"
      >
        <el-icon><Plus /></el-icon>
        新增用户
      </el-button>
    </div>

    <!-- 用户列表 -->
    <el-card>
      <el-table :data="userList" v-loading="loading" style="width: 100%">
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="roles" label="角色">
          <template #default="{ row }">
            <el-tag
              v-for="role in row.roles"
              :key="role.id"
              style="margin-right: 8px"
            >
              {{ role.name }}
            </el-tag>
            <el-tag v-if="!row.roles || row.roles.length === 0" type="info">
              未分配角色
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="permissions" label="权限数量">
          <template #default="{ row }">
            <el-tag>{{ row.permissionCount || 0 }} 个权限</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginAt" label="最后登录">
          <template #default="{ row }">
            {{ row.lastLoginAt ? formatDate(row.lastLoginAt) : "从未登录" }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                size="small"
                @click="handleAssignRoles(row)"
                v-permission="'system:user:edit'"
              >
                分配角色
              </el-button>
              <el-button
                size="small"
                @click="handleViewPermissions(row)"
                v-permission="'system:user:view'"
              >
                查看权限
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleDeleteUser(row)"
                :disabled="row.username === 'admin'"
                v-permission="'system:user:delete'"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 角色分配对话框 -->
    <el-dialog v-model="roleDialogVisible" title="分配角色" width="50%">
      <div class="role-assign">
        <p>
          为用户 <strong>{{ currentUser?.username }}</strong> 分配角色：
        </p>
        <el-checkbox-group v-model="selectedRoles">
          <el-checkbox
            v-for="role in roleList"
            :key="role._id"
            :label="role._id"
            :disabled="
              role.code === 'super_admin' && currentUser?.username !== 'admin'
            "
          >
            {{ role.name }} - {{ role.description }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveRoles">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限查看对话框 -->
    <el-dialog v-model="permissionDialogVisible" title="用户权限" width="60%">
      <div class="permission-view">
        <p>
          用户 <strong>{{ currentUser?.username }}</strong> 的权限列表：
        </p>
        <div v-if="userPermissions.length > 0">
          <div
            v-for="module in groupedPermissions"
            :key="module.name"
            class="permission-module"
          >
            <h4>{{ module.name }}</h4>
            <el-tag
              v-for="permission in module.permissions"
              :key="permission.id"
              style="margin: 4px 8px 4px 0"
              :type="permission.type === 'menu' ? 'primary' : 'success'"
            >
              {{ permission.name }}
            </el-tag>
          </div>
        </div>
        <el-empty v-else description="该用户暂无权限" />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import request from "../../utils/request";

// 响应式数据
const loading = ref(false);
const userList = ref([]);
const roleList = ref([]);
const roleDialogVisible = ref(false);
const permissionDialogVisible = ref(false);
const selectedRoles = ref([]);
const currentUser = ref(null);
const userPermissions = ref([]);

// 计算属性：按模块分组的权限
const groupedPermissions = computed(() => {
  const moduleMap = new Map();

  userPermissions.value.forEach((permission) => {
    const moduleName = getModuleName(permission.module);
    if (!moduleMap.has(moduleName)) {
      moduleMap.set(moduleName, {
        name: moduleName,
        permissions: [],
      });
    }
    moduleMap.get(moduleName).permissions.push(permission);
  });

  return Array.from(moduleMap.values());
});

// 获取用户列表（优化版本 - 后端已包含角色信息）
const getUserList = async () => {
  try {
    loading.value = true;

    // 从后端获取用户列表（已包含角色信息）
    const response = await request({
      url: "/jjx/users",
      method: "GET",
    });

    if (response.success) {
      userList.value = response.data;
    } else {
      ElMessage.error("获取用户列表失败");
    }
  } catch (error) {
    console.error("获取用户列表失败:", error);
    ElMessage.error("获取用户列表失败");
  } finally {
    loading.value = false;
  }
};

// 注：getUserRoles 函数已删除，角色信息现在直接从用户列表接口获取

// 获取角色列表（带缓存）
const getRoleList = async () => {
  // 如果已有数据，不重复请求
  if (roleList.value.length > 0) {
    return;
  }

  try {
    const response = await request({
      url: "/jjx/roles",
      method: "GET",
    });
    if (response.success) {
      roleList.value = response.data;
    }
  } catch (error) {
    console.error("获取角色列表失败:", error);
  }
};

// 获取模块名称
const getModuleName = (module: string) => {
  const moduleNames = {
    system: "系统管理",
    doctor: "医生管理",
    patient: "患者管理",
    appointment: "预约管理",
    finance: "财务管理",
  };
  return moduleNames[module] || module;
};

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return "-";
  return new Date(dateString).toLocaleDateString("zh-CN");
};

// 新增用户
const handleAddUser = () => {
  ElMessage.info("新增用户功能开发中...");
};

// 分配角色
const handleAssignRoles = async (user: any) => {
  currentUser.value = user;
  selectedRoles.value = user.roles?.map((r) => r._id || r.id) || [];
  roleDialogVisible.value = true;

  // 获取角色列表
  if (roleList.value.length === 0) {
    await getRoleList();
  }
};

// 查看权限
const handleViewPermissions = async (user: any) => {
  currentUser.value = user;

  try {
    const response = await request({
      url: `/jjx/users/${user._id}/permissions`,
      method: "GET",
    });
    if (response.success) {
      userPermissions.value = response.data;
      permissionDialogVisible.value = true;
    }
  } catch (error) {
    console.error("获取用户权限失败:", error);
  }
};

// 保存角色分配
const handleSaveRoles = async () => {
  try {
    const response = await request({
      url: `/jjx/users/${currentUser.value._id}/roles`,
      method: "POST",
      data: {
        roleIds: selectedRoles.value,
      },
    });

    if (response.success) {
      ElMessage.success("角色分配成功");
      roleDialogVisible.value = false;
      getUserList(); // 刷新列表
    }
  } catch (error) {
    console.error("保存角色失败:", error);
  }
};

// 删除用户
const handleDeleteUser = async (user: any) => {
  ElMessage.info("删除用户功能开发中...");
};

// 页面加载时获取数据
onMounted(() => {
  getUserList();
});
</script>

<style lang="scss" scoped>
.system-users {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    .page-title {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      color: #333;
    }
  }

  .role-assign {
    .el-checkbox-group {
      display: flex;
      flex-direction: column;
      gap: 12px;
      margin-top: 16px;
    }
  }

  .permission-view {
    .permission-module {
      margin-bottom: 20px;

      h4 {
        margin: 0 0 12px 0;
        color: #409eff;
        font-size: 16px;
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }

  // 操作按钮样式
  .action-buttons {
    display: flex;
    gap: 8px;
    align-items: center;
    flex-wrap: nowrap; // 防止换行

    .el-button {
      margin: 0; // 重置默认margin
      white-space: nowrap; // 防止按钮文字换行
    }
  }
}
</style>